import { NestFactory } from '@nestjs/core';
import * as fs from 'fs';
import { AppModule } from './app.module';
import { NestExpressApplication } from '@nestjs/platform-express';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { AllExceptionFilter } from './core/filters/all-exception.filter';
import { HttpReqTransformInterceptor } from './core/interceptors/http-req.interceptor';
import { Logger } from '@nestjs/common';
import { join } from 'path';
import { PrefixMiddleware } from './core/middleware/prefix.middleware';
import { getMySqlConfig, post } from './config/mySql';
declare const module: any;

async function bootstrap() {
  process.env.TZ = 'Asia/Shanghai';

  // 手动加载环境变量

  // 使用express作为默认配置
  const app = await NestFactory.create<NestExpressApplication>(AppModule);
  app.enableCors();
  app.useStaticAssets(join(__dirname, '/uploads'), {
    prefix: '/static/', //设置虚拟前缀路径
    maxAge: 1000 * 60, //设置缓存时间
  });

  // 全局异常过滤
  app.useGlobalFilters(new AllExceptionFilter());
  // 全局拦截器
  app.useGlobalInterceptors(new HttpReqTransformInterceptor());

  // swagger配置
  const options = new DocumentBuilder()
    .setTitle('接口文档')
    .setDescription('')
    .addBearerAuth()
    .setVersion('3.0')
    .build();

  const documents = SwaggerModule.createDocument(app, options);
  fs.writeFileSync('./swagger-spec.json', JSON.stringify(documents));
  SwaggerModule.setup('/api', app, documents);

  await app.listen(post, '0.0.0.0');
  const serverUrl = await app.getUrl();
  Logger.log(`api服务已经启动,请访问: ${serverUrl}`);
  Logger.log(`API文档已生成,请访问: ${serverUrl}/api/`);

  // // 热重载
  // if (module.hot) {
  //   module.hot.accept();
  //   module.hot.dispose(() => app.close());
  // }
}
bootstrap();
